﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCMS.CoreBusinessLogic.ProcurementPlan;
using SCMS.CoreBusinessLogic.Web;
using SCMS.CoreBusinessLogic.Security;
using SCMS.Model;
using SCMS.UI.Models;
using SCMS.CoreBusinessLogic.OrderRequest;
using SCMS.CoreBusinessLogic._CountrySubOffice;
using System.Text;
using SCMS.CoreBusinessLogic.NotificationsManager;

namespace SCMS.UI.Controllers
{
    public class ProcurementPlanController : PortalBaseController
    {
        private IProcurementPlanService ppService;
        private IOrderRequest orService;
        private ICountrySubOfficeService csoService;
        private INotificationService notificationService;

        public ProcurementPlanController(IProcurementPlanService ppService, IOrderRequest orService, ICountrySubOfficeService csoService, IUserContext uc, 
            IPermissionService permService, INotificationService notificationService)
            : base(uc, permService)
        {
            this.ppService = ppService;
            this.orService = orService;
            this.csoService = csoService;
            this.notificationService = notificationService;
        }
        //
        // GET: /ProcurementPlan/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ViewPPList()
        {
            List<ProcurementPlan> model = ppService.GetProcurementPlans(countryProg.Id);
            return View("ViewPPList", model);
        }

        public ActionResult ViewPP(Guid id)
        {
            PPModel model = PreparePPModel(id, false);
            return View("ViewPP", model);
        }

        public ActionResult ViewPPItems(Guid id, string type)
        {
            List<PPItemModel>  model = new List<PPItemModel>();
            List<Model.ProcurementPlanItem> ppItems = ppService.GetProcurementPlanItems(id);
            if (type == "all")
            {
                foreach (ProcurementPlanItem ppItem in ppItems)
                {
                    if (ppItem.IsApproved)
                        model.Add(new PPItemModel { EntityPPItem = ppItem });
                }
                ViewBag.AllStyle = "font-weight: bold;";
                ViewBag.NoResultsMsg = "PP has no items set yet";
            }
            else if (type == "active")
            {
                foreach (ProcurementPlanItem ppItem in ppItems)
                {
                    if (ppItem.AddedToOR || !ppItem.IsApproved)
                        continue;
                    model.Add(new PPItemModel { EntityPPItem = ppItem });
                }
                ViewBag.ActiveStyle = "font-weight: bold;";
                ViewBag.NoResultsMsg = "PP has no activie items";
            }
            else if (type == "inactive")
            {
                foreach (ProcurementPlanItem ppItem in ppItems)
                {
                    if (!ppItem.AddedToOR || !ppItem.IsApproved)
                        continue;
                    model.Add(new PPItemModel { EntityPPItem = ppItem });
                }
                ViewBag.InActiveStyle = "font-weight: bold;";
                ViewBag.NoResultsMsg = "PP has no inactive items";
            }
            else if (type == "removed")
            {
                foreach (ProcurementPlanItem ppItem in ppItems)
                {
                    if (!ppItem.IsRemoved || !ppItem.IsApproved)
                        continue;
                    model.Add(new PPItemModel { EntityPPItem = ppItem });
                }
                ViewBag.RemovedStyle = "font-weight: bold;";
                ViewBag.NoResultsMsg = "PP has no removed items";
            }
            ViewBag.PPId = id;
            return View("PPItemsList", model);
        }

        private PPModel PreparePPModel(Guid id, bool editMode)
        {
            ProcurementPlan pp = ppService.GetProcurementPlanById(id);
            PPModel model = new PPModel { EntityPP = pp };
            model.PPItems = new List<PPItemModel>();
            List<Model.ProcurementPlanItem> ppItems = ppService.GetProcurementPlanItems(pp.Id);
            foreach (ProcurementPlanItem ppItem in ppItems)
                if(editMode && !ppItem.IsRemoved && !ppItem.AddedToOR)
                    model.PPItems.Add(new PPItemModel { EntityPPItem = ppItem });
                else if (ppItem.IsApproved)
                    model.PPItems.Add(new PPItemModel { EntityPPItem = ppItem });
            return model;
        }

        public ActionResult CreatePP()
        {
            PPModel model = new PPModel();
            model.EntityPP = new ProcurementPlan { RefNumber = "--NEW PP--"};
            model.Projects = new SelectList(orService.GetProject(countryProg.Id), "Id", "Name");
            model.ProjectDonors = new SelectList(orService.GetProjectNos(countryProg.Id, Guid.Empty), "Id", "ProjectNumber");
            model.SubOffices = new SelectList(csoService.GetCountrySubOffices(countryProg.Id), "Id", "Name");
            model.EntityPP.PreparedOn = DateTime.Today;
            ViewBag.FormHeader = "New Procurement Plan";
            return View("CreatePP", model);
        }

        public ActionResult EditPP(Guid Id)
        {
            ProcurementPlan pp = ppService.GetProcurementPlanById(Id);
            PPModel model = new PPModel();
            model.EntityPP = pp;
            model.ProjectId = pp.ProjectDonor.ProjectId;
            model.Projects = new SelectList(orService.GetProject(countryProg.Id), "Id", "Name", model.ProjectId);
            model.ProjectDonors = new SelectList(orService.GetProjectNos(countryProg.Id, pp.ProjectDonor.ProjectId), "Id", "ProjectNumber", pp.ProjectDonorId);
            model.SubOffices = new SelectList(csoService.GetCountrySubOffices(countryProg.Id), "Id", "Name", pp.PreparingOfficeId);
            ViewBag.FormHeader = "Edit Procurement Plan :: " + pp.RefNumber;
            ViewBag.Donor = pp.ProjectDonor.Donor.Name;
            return View("CreatePP", model);
        }

        [HttpPost]
        public ActionResult SaveProcPlan(PPModel model)
        {
            model.EntityPP.PreparedBy = currentStaff.Id;
            ppService.SaveProcurementPlan(model.EntityPP);
            return PPDetails(model.EntityPP.Id);
        }

        public ActionResult SubmitPP(Guid id)
        {
            ProcurementPlan pp = ppService.GetProcurementPlanById(id);
            notificationService.SendToAppropriateApprover(NotificationHelper.ppCode, NotificationHelper.approvalCode, pp.Id);
            return ViewPPList();
        }

        public ActionResult PPDetails(Guid Id)
        {
            PPModel model = PreparePPModel(Id, true);
            return View("CreatePPStep2", model);
        }

        public ActionResult GetProjectNumbers(Guid projectId)
        {
            StringBuilder pdOption = new StringBuilder();
            pdOption.Append("<select id=\"dplProNo\" name=\"EntityPP.ProjectDonorId\" onchange=\"javascript:GetDonor(this)\">");
            pdOption.Append("<option value=\"\">--Please Select--</option>");
            List<Model.ProjectDonor> pdList = orService.GetProjectNos(countryProg.Id, projectId);
            foreach (ProjectDonor item in pdList)
                pdOption.Append("<option value=\"" + item.Id + "\">" + item.ProjectNumber + "</option>");
            pdOption.Append("</select>");
            pdOption.Append("<span class=\"field-validation-valid\" data-valmsg-for=\"EntityPP.ProjectDonorId\" data-valmsg-replace=\"false\">Required</span>");
            return Content(pdOption.ToString(), "text/html");
        }

        public ActionResult CreatePPItem(Guid ppId)
        {
            PPItemModel model = new PPItemModel();
            ProcurementPlan pp = ppService.GetProcurementPlanById(ppId);
            model.Items = new SelectList(orService.GetItems(countryProg.Id), "Id", "Name");
            model.BudgetLines = new SelectList(orService.GetProjectBugdetLines(pp.ProjectDonorId), "Id", "Description");
            model.EntityPPItem = new ProcurementPlanItem { ProcurementPlanId = ppId, CurrencyId = countryProg.Country.CurrencyId.Value, RequiredDeliveryDate = DateTime.Today };
            model.Currencies = new SelectList(orService.GetCurrencies(countryProg.Id), "Id", "ShortName", countryProg.Country.CurrencyId);
            model.Locations = new SelectList(orService.GetLocations(countryProg.Id), "Id", "Name");
            ViewBag.Action = "Add Item";
            return View("CreatePPItem", model);
        }

        public ActionResult SaveProcPlanItem(PPItemModel model)
        {
            ppService.SaveProcurementPlanItem(model.EntityPPItem);
            return PPDetails(model.EntityPPItem.ProcurementPlanId);
        }

        public ActionResult EditPPItem(Guid id)
        {
            ProcurementPlanItem ppItem = ppService.GetProcurementPlanItemById(id);
            PPItemModel model = new PPItemModel();
            model.Items = new SelectList(orService.GetItems(countryProg.Id), "Id", "Name");
            model.BudgetLines = new SelectList(orService.GetProjectBugdetLines(ppItem.ProcurementPlan.ProjectDonorId), "Id", "Description");
            model.EntityPPItem = ppItem;
            model.EntityPPItem.UnitCost = Math.Round(model.EntityPPItem.UnitCost, 2);
            model.EntityPPItem.TotalCost = Math.Round(model.EntityPPItem.TotalCost, 2);
            model.Currencies = new SelectList(orService.GetCurrencies(countryProg.Id), "Id", "ShortName");
            model.Locations = new SelectList(orService.GetLocations(countryProg.Id), "Id", "Name");
            ViewBag.Action = "Update";
            return View("CreatePPItem", model);
        }

        public ActionResult RemovePPItem(Guid id)
        {
            ProcurementPlanItem ppItem = ppService.GetProcurementPlanItemById(id);
            ppService.DeleteProcurementPlanItem(id);
            return PPDetails(ppItem.ProcurementPlanId);
        }

        public ActionResult DeletePP(Guid id)
        {
            ppService.DeleteProcumentPlan(id);
            return ViewPPList();
        }
    
    }
}
